import {parsedSfxFiles} from "./getSfxLibrary";
import fs from "fs";
import path from "path";

const BASE_PATH = path.join(process.env.LOCALAPPDATA, "GeometryDash")

/**
 * @async
 * @param {number} id - The id of the sound effect to download.
 */
export async function downloadSfx(id) {
  const sfxToDownload = parsedSfxFiles.find((el) => el.id === id);
  if (!sfxToDownload) {
    throw new Error(`Could't find the sound effect specified (${id})`);
  }

  if (sfxToDownload.id === 1) {
    console.error(
      `Sound effect with id 1 is reserved for the version of the sfx library. This is not an error.`
    );
    return;
  }

  if (sfxToDownload.isFolder) {
    /*
    if (!fs.existsSync(`sfx/${sfxToDownload.name}`)) {
      fs.mkdirSync(`sfx/${sfxToDownload.name}`);
    }
      */
     console.warn(`Sfx ${id} is folder, skipping.`);
     return;
  }

  if (fs.existsSync(path.join(BASE_PATH, `s${id}.ogg`))) {
    /*
    if (!fs.existsSync(`sfx/${sfxToDownload.name}`)) {
      fs.mkdirSync(`sfx/${sfxToDownload.name}`);
    }
      */
     console.info(`Sfx ${id} already exists, skipping.`);
     return;
  }

  const url = `https://geometrydashfiles.b-cdn.net/sfx/s${id}.ogg`;
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Response staus: ${response.status}. Id is ${id}`);
    }

   

    const downloadBuffer = await response.arrayBuffer();
    fs.writeFileSync(path.join(BASE_PATH, `s${id}.ogg`), downloadBuffer);
  } catch (error) {
    console.error(error.message);
  }
}
